package org.example.Polls;

public class DefaultServiceFactory implements ServiceFactory {
	
	private static DefaultServiceFactory instance = null;
	public static final String MOCK_IMPLEMENTATION = "org.example.Polls.MockServiceFactory";
	public static final String SOAP_IMPLEMENTATION = "org.example.Polls.SOAPServiceFactory";
	
	private String serviceFactoryImpl;
	private ServiceFactory serviceFactory;
	private UserService userService;
	private PollService pollService;
	
	private DefaultServiceFactory(String serviceFactoryImpl) {
		setServiceFactoryImpl(serviceFactoryImpl);
	}
	
	public static DefaultServiceFactory getInstance() {
		try {
    		if (instance == null) {
    			//instance = new DefaultServiceFactory(MOCK_IMPLEMENTATION);
    			instance = new DefaultServiceFactory(SOAP_IMPLEMENTATION);
    		}
    		return instance;
		} catch (Exception e) {
			throw new RuntimeException("Unable to create default service factory");
			
		}
	}
	
	public String getServiceFactoryImpl() {
		return this.serviceFactoryImpl;	
	}
	
	public void setServiceFactoryImpl(String serviceFactoryImpl) {
		try {
			this.serviceFactory = (ServiceFactory)Class.forName(serviceFactoryImpl).newInstance();
			this.serviceFactoryImpl = serviceFactoryImpl;
			this.userService = this.serviceFactory.createUserService();
			this.pollService = this.serviceFactory.createPollService();
		} catch (Exception e) {
			throw new RuntimeException("Unable to set service factory implementation", e);
		}
	}

	public UserService createUserService() {
		return this.userService;
	}

	public PollService createPollService() {
		return this.pollService;
	}

}
